<?php
use think\Controller;
use app\admin\model\SystemParamValue;
// 应用公共文件

//错误级别
error_reporting(E_ERROR | E_PARSE );

/**
 * 获取系统参数
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function getSystem($paramCode,$parentValue=-1)
{
	$param["param_code"] = $paramCode;
	if($parentValue!=-1){
		$param["parent_value"] = $parentValue;
	}
	$value = SystemParamValue::where($param)->value("param_value");
	if( $value === null  && $parentValue !=-1 ){
		$param["parent_value"] = 0;
		$value = SystemParamValue::where($param)->value("param_value");
	}
	return  $value;
}


/**
 * 获取方法注释
 * @func_code  。。。
 * @action_code 。。。
 * @is_need_login true
 * @method all
 */
function get_method_desc(){
	$request = request();
	$act = 'app'.'\\'.$request->module().'\controller';
	$controller = explode(".",$request->controller());
	foreach($controller as $key=>$val){
		if($key < count($controller) -1 ){
			$str = lcfirst($val);
		}else{
			$str = ucwords($val);
		};
		$act = $act.'\\'.$str;
	}
	$data = ['func_code'=>'','action_code'=>'', 'is_need_login'=>'true','method'=>'all',"is_vip"=>"false"];
	try {
      	$func  = new \ReflectionMethod($act,request()->action());
		$tmp   = $func->getDocComment();
		foreach($data as $key=>$val){
			preg_match_all('/@'.$key.'(.*?)\n/',$tmp,$code);
			$code = trim($code[1] ? $code[1][0] : '');
			$data[$key] = $code !='' ? $code: $data[$key];
		}
	} catch (\Exception $e) {
		$data['is_need_login'] = 'true';
	}
	return $data;
}


/**
 * 获取当前路径
 * @param  null
 */
function get_active_url(){
	$request= request();
	$module_name=$request->module();
	$controller_name=$request->controller();
	$action= $request->action();
	$active_url=$module_name.'/'.$controller_name.'/'.$action;
	return $active_url;
}


/**
 * 获取guid
 * @param  null
 */
function get_uuid() {
    list($usec, $sec) = explode(" ", microtime(false));
    $usec = (string)($usec * 10000000);
    $timestamp = bcadd(bcadd(bcmul($sec, "10000000"), (string)$usec), "621355968000000000");
    $ticks = bcdiv($timestamp, 10000);
    $maxUint = 4294967295;
    $high = bcdiv($ticks, $maxUint) + 0;
    $low = bcmod($ticks, $maxUint) - $high;
    $highBit = (pack("N*", $high));
    $lowBit = (pack("N*", $low));
    $guid = str_pad(dechex(ord($highBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($highBit[3])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[0])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[1])), 2, "0", STR_PAD_LEFT) . "-" . str_pad(dechex(ord($lowBit[2])), 2, "0", STR_PAD_LEFT) . str_pad(dechex(ord($lowBit[3])), 2, "0", STR_PAD_LEFT) . "-";
    $chars = "abcdef0123456789";
    for ($i = 0; $i < 4; $i++) {
        $guid .= $chars[mt_rand(0, 15)];
    }
    $guid .= "-";
    for ($i = 0; $i < 4; $i++) {
        $guid .= $chars[mt_rand(0, 15)];
    }
    $guid .= "-";
    for ($i = 0; $i < 12; $i++) {
        $guid .= $chars[mt_rand(0, 15)];
    }
    return $guid;
}


/**
 * 数据库多语句查询
 * @param  $sqls
 */
function db_multi_query($sqls=""){
	$data=array();
	$c = config()['database'];
	$conn = new \mysqli( $c['hostname'], $c['username'],$c['password'],$c['database'],$c['hostport']);
	if (mysqli_connect_errno($conn)){
		throw new \think\Exception( "连接到 MySQL 失败: " . mysqli_connect_error() );
	}else{
		$conn->query("set names utf8");
		if(mysqli_multi_query($conn, $sqls)) {
	        do {
	            if($result = mysqli_store_result($conn)) {
	                while( $row = mysqli_fetch_assoc($result)  ) {
	                	array_push($data, $row);
	                }
	                mysqli_free_result($result);        
	            }
	        } while(mysqli_next_result($conn));
	    }
		if($conn->error){
			mysqli_close($conn);
			throw new \think\Exception( 'error:  ' . $conn->error );
		}
	    mysqli_close($conn);
	}
	return $data;
}


/**
 * 去掉？后的参数
 * @param  string $url 
 */
function clear_urlcan($url){
    $rstr='';
    $tmparr = parse_url($url);
    $rstr = empty($tmparr['scheme']) ? '' : $tmparr['scheme'].'://';
    $rstr.= $tmparr['host'].$tmparr['path'];
    return $rstr;
}


/**
 * 生成查询条件 
 * @param $where = [{opera: "like", field: "address", value: "阿斯顿撒"}]
 * @return  $where[] =['address',"like","%阿斯顿撒%"]
 */
function create_where($where){
	$w = [];
    foreach($where as $key => $v){
    	$opera = $v['opera'];  $field = $v['field']; $value = $v['value'];
		//like
    	$value = $opera == 'like' ? "%".$value."%" : $value;
		//逗号分割多个字段
		$field = str_replace(",",'|',$field);
		//时间类型
		if($v["type"] == 'date'){  $opera = $opera." time"; }
		//存储
		$w[] = [ $field,  $opera , $value];
	}
	return $w;
}

/* 
* 
*事件 
*/  
function event($eventName,$param=[])  {
	$myarr = include base_path()."/application/event.php";
    $result = '';
    $eventName =  'on'.$eventName;
	foreach ($myarr['subscribe'] as $key => $value) {
		$value = str_replace("\\","/",$value); 
		$value = str_replace("app/","/application/",$value); 
		$value = str_replace("/application//application/","/application/app/",$value); 
		require_once  base_path().$value.'.php';
        try {
            $object = explode("/",$value);
            $object = $object[count($object)-1];
            $subscribe = new $object();
            if(method_exists($subscribe,$eventName)){
			    $result = $subscribe->$eventName($param);
			}
        } catch (\Exception $e) {
            
        }
	}
	return $result;
};



/* 
* 
*路径自定义函数 
*/ 
function base_path($path = ''){
    return env('root_path').($path ? ltrim($path, DIRECTORY_SEPARATOR) : ltrim($path, DIRECTORY_SEPARATOR));
}
function public_path($path = ''){
    return base_path('public').($path ? DIRECTORY_SEPARATOR.$path : $path);
}
function windows_os() {
    return strtolower(substr(PHP_OS, 0, 3)) === 'win';
}
function storage_path($path = '') {
    return base_path().'storage'.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
function views_path($path = '') {
    return base_path().'views'.($path ? DIRECTORY_SEPARATOR.$path : $path);
}
